package com.yh.csx.etl.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.yaml.snakeyaml.Yaml;

/**
 * Yaml 工具类
 * 
 * @author Robin.Wang
 * @date 2020-03-18
 *
 */

public class YamlUtils {

    private static final Logger log = LoggerFactory.getLogger(YamlUtils.class);

    /**
     * 加载对象
     * 
     */
    public static Object load(String filePath) {
        Yaml yaml = new Yaml();
        Object ret = yaml.load(filePath);
        return ret;
    }

    /**
     * 加载yaml配置的实例对象
     * 
     * @param filepath yaml文件路径
     * @param clazz    类型
     */
    public static <T> T loadFromFile(String filePath, Class<T> clazz) throws FileNotFoundException {
        Assert.notNull(filePath, "filePath is null");
        Yaml yaml = new Yaml();
        T ret = yaml.loadAs(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8), clazz);
        return ret;
    }

    /**
     * 加载yaml对象
     * 
     * @param content yaml内容
     * @param clazz   返回对象类型
     */
    public static <T> T load(String content, Class<T> clazz) {
        Yaml yaml = new Yaml();
        T ret = yaml.loadAs(content, clazz);
        return ret;
    }

    /**
     * 保存对象为yaml格式文件
     * 
     * @param t    数据对象
     * @param path 输出路径
     * @throws IOException
     */
    public static <T> void save(T t, String path) throws IOException {

        Yaml yaml = new Yaml();
        try (FileWriter file = new FileWriter(path)) {
            file.write(yaml.dumpAsMap(t));
            file.flush();
        }

    }

}
